<template>
  <view class="page">
    <u-navbar @leftClick="navLeftClick" :fixed="false" title="邀请好友" placeholder bgColor="#fff"></u-navbar>
    <view class="invite-people">
      <view class="u-flex">
        <image style="width: 40rpx;height: 40rpx;flex-shrink: 0;margin-right: 12rpx;" src="../../static/my/people.png" />
        <text class="u-font-28">我的邀请人</text>
      </view>
      <view class="u-font-28" v-if="userInfo.invitationName">{{ userInfo.invitationName }}</view>
      <view class="u-flex u-font-28" v-else @click="showInvite=true">
        <text class="u-m-r-18" style="color: #919191;">填写邀请人</text>
        <u-icon color="#000" size="20rpx" name="arrow-right"></u-icon>
      </view>
    </view>
    <canvas canvas-id="myCanvas" @click="saveCanvas" id="myCanvas" class="invite-banner" style="position: fixed;left: -2000rpx;" />
    <image :src="tempFilePath" class="invite-banner" />
    <view class="invite-list">
      <image v-for="item in list" :key="item.id" :class="{active: invite == item.posterUrl}" @click="check(item.posterUrl)" style="width: 100rpx;height: 100rpx;" :src="item.posterUrl" mode="aspectFill" />
    </view>
    <view class="invite-info">
      <view class="u-flex u-row-between u-p-b-18 u-p-t-18">
        <view class="u-font-28">我的邀请码：</view>
        <view class="u-flex u-font-28" @click="copy">
          <text class="u-m-r-14">{{ userInfo.invitationCode }}</text>
          <image style="width: 24rpx;height: 23.69rpx;" src="../../static/my/copy.png" />
        </view>
      </view>
      <view class="u-flex u-row-between u-p-b-18 u-p-t-18">
        <view class="u-font-28">我的团队数量：</view>
        <view class="u-flex u-font-28">
          <text class="u-m-r-14" style="color: #56CB03;">{{ teamTotal }}</text>
        </view>
      </view>
      <view class="u-flex u-row-between u-p-b-18 u-p-t-18">
        <view class="u-font-28">我的好友列表：</view>
        <view class="u-flex u-font-28" @click="jumpTo('/pages/my/inviteList')">
          <text class="u-m-r-14" style="color: #56CB03;">{{ total }}</text>
          <u-icon color="#000" size="20rpx" name="arrow-right"></u-icon>
        </view>
      </view>
    </view>
    <u-popup :show="showInvite" :round="20" mode="center" @close="showInvite=false">
      <view class="invite-popup customize-popup">
        <view class="popup-title">我的邀请人</view>
        <view class="popup-input">
          <u--input
            placeholder="请输入邀请码"
            border="surround"
            v-model="inviteCode"
          ></u--input>
        </view>
        <!-- <view class="popup-tips">*邀请码不存在</view> -->
        <view class="btn-list">
          <view class="btn-item" style="color: #56CB03;background-color: #fff;" @click="showInvite=false">取消</view>
          <view class="btn-item" style="color: #fff;background-color: #56CB03;" @click="submitInviteCode">确定</view>
        </view>
      </view>
		</u-popup>
  </view>
</template>

<script>
import qrcode from 'qrcode'
import inviteBg from '../../static/my/invite.png'
import { saveInviteCode, getUserList, getPosterInfoList, getTeamNum } from '@/api/index'

export default {
  data() {
    return {
      invite: '',
      showInvite: false,
      inviteCode: '',
      userInfo: {},
      total: 0,
      teamTotal: 0,
      list: [],
      imgCode: '',
      load: false,
      tempFilePath: '',
    };
  },
  onLoad() {
    this.userInfo = uni.getStorageSync('userInfo')
    this.getPage()
    qrcode.toDataURL(this.httpUrl + '?invitationCode='+this.userInfo.invitationCode, {width: 200, height: 200}, (err, url) => {
      if (err) {
        uni.showToast({
          title: '邀请二维码生成失败',
          icon: 'none',
          mask: true,
        });
      } else {
        this.imgCode = url
      }
    });
  },
  methods: {
    getPage() {
      getPosterInfoList({ pageSize: 6, status: '1' }).then(res => {
        this.list = res.rows
        if(this.list.length) {
          this.invite = res.rows[0].posterUrl
        } else {
          this.invite = inviteBg
        }
        this.drawImages()
      })
      getUserList({ invitationBy: this.userInfo.invitationCode, pageSize: 1, }).then(res => {
        this.total = res.total
      })
      getTeamNum({userId: this.userInfo.userId}).then(res => {
        this.teamTotal = res.data || 0
      })
    },
    async drawImages() {
      // 获取Canvas实际尺寸
      const canvasInfo = await this.getCanvasInfo();
      const canvasWidth = canvasInfo.width;
      const canvasHeight = canvasInfo.height;
      
      const ctx = uni.createCanvasContext('myCanvas', this);
      
      // 先绘制底图
      ctx.drawImage(this.invite, 0, 0, canvasWidth, canvasInfo.height);
      
      // 二维码尺寸（根据需求调整）
      const qrCodeWidth = 80;
      const qrCodeHeight = 80;
      
      // 计算居中位置
      const centerX = (canvasWidth - qrCodeWidth) / 2;
      
      // 绘制二维码
      // ctx.drawImage(this.imgCode, centerX, 132, qrCodeWidth, qrCodeHeight);
      ctx.drawImage(this.imgCode, canvasWidth - 82, canvasHeight - 82, qrCodeWidth, qrCodeHeight);
      
      ctx.draw(false, async () => {
        console.log('图片绘制完成');
        const { tempFilePath } = await uni.canvasToTempFilePath({
          canvasId: 'myCanvas'
        }, this);
        this.tempFilePath = tempFilePath
        this.load = true
      });
    },
    // 获取Canvas信息
    getCanvasInfo() {
      return new Promise((resolve) => {
        const query = uni.createSelectorQuery().in(this);
        query.select('#myCanvas').boundingClientRect(rect => {
          resolve(rect);
        }).exec();
      });
    },
    check(url) {
      this.invite = url
      this.drawImages()
    },
    saveCanvas() {
      if(!this.load) {
        uni.showToast({ title: '海报还未加载完成', icon: 'none' });
        return
      }
      uni.showToast({ title: '长按下载', icon: 'none' });
      return
      uni.showModal({
        title: '提示',
        content: '确定下载海报到本地?',
        showCancel: true,
        success: async ({ confirm, cancel }) => {
          if(confirm) {
            // 转换为图片
            const { tempFilePath } = await uni.canvasToTempFilePath({
              canvasId: 'myCanvas'
            }, this);
            
            // 保存到相册
            // await uni.saveImageToPhotosAlbum({
            //   filePath: tempFilePath
            // });
            uni.showLoading({ mask: true })
            const link = document.createElement('a');
            link.href = tempFilePath;
            link.setAttribute('download', '图片.png');
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            uni.hideLoading();
            uni.showToast({ title: '保存成功', icon: 'none' });
          }
        }
      })
    },
    copy() {
      uni.setClipboardData({
        data: this.userInfo.invitationCode + '',
        success: function () {
          uni.showToast({
            title: '复制成功',
            icon: 'none'
          })
        }
      });
    },
    submitInviteCode() {
      if(uni.$u.trim(this.inviteCode, 'all') === '') {
        uni.showToast({
          title: '请输入邀请码',
          icon: 'none'
        })
        return
      }
      const parameter = {
        userId: this.userInfo.userId,
        invitationCode: uni.$u.trim(this.inviteCode, 'all'),
      }
      saveInviteCode(parameter).then(res => {
        getUserInfo({}).then(res => {
          uni.setStorageSync('userInfo', {...res.user, roles: res.roles})
          this.userInfo = {...res.user, roles: res.roles}
        })
      })
    },
  },
};
</script>

<style lang="scss" scoped>
.page {
  width: 750rpx;
  min-height: 100vh;
  background-color: #F5F5F5;
  padding-bottom: 80rpx;
  position: relative;
  .invite-people {
    width: 702rpx;
    height: 100rpx;
    margin: 12rpx auto;
    background-color: #fff;
    border-radius: 12rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 22rpx;
  }
  .invite-banner {
    width: 702rpx;
    height: 1002rpx;
    display: block;
    background-repeat: no-repeat;
    background-size: 702rpx 1002rpx;
    margin: 0 auto 12rpx;
    position: relative;
    border-radius: 12rpx;
  }
  .invite-list {
    width: 702rpx;
    padding: 12rpx 0;
    display: flex;
    gap: 14rpx;
    margin: 0 auto;
    .active {
      border: 2rpx solid #04C15F;
    }
  }
  .invite-info {
    width: 702rpx;
    background-color: #fff;
    border-radius: 12rpx;
    padding: 20rpx 22rpx;
    margin: 0 auto;
  }
}
.invite-popup {
  width: 632rpx;
  background-color: #fff;
  border-radius: 20rpx;
  padding-top: 60rpx;
  padding: 60rpx 24rpx 28rpx;
  .popup-input {
    margin-bottom: 16rpx;
  }
  .popup-tips {
    font-size: 24rpx;
    color: rgba(226, 3, 0, 1);
    text-align: center;
    margin-bottom: 16rpx;
  }
  .btn-list {
    display: flex;
    gap: 24rpx;
    .btn-item {
      flex: 1;
      height: 80rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 2rpx solid #56CB03;
      background-color: #FCDDBA;
      font-size: 28rpx;
      border-radius: 200rpx;
    }
  }
}
</style>
